from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ
from meiduo_mall import settings
from oauth.models import OAuthQQUser
from oauth.serializers import OAuthQQUserSerializer
from oauth.utils import generic_openid_token


class OAuthQQUrlAPIView(APIView):

    def get(self,request):

        state = "/"
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI, state=state)
        auth_url = qq.get_qq_url()

        return Response({"auth_url":auth_url})

class OAuthQQUserAPIView(APIView):

    def get(self,request):

        code = request.query_params.get("code")
        if code is None:
            from rest_framework import status
            return Response(status=status.HTTP_400_BAD_REQUEST)

        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI)
        token = qq.get_access_token(code)
        openid = qq.get_open_id(token)

        try:
            qquser= OAuthQQUser.objects.get(openid = openid)
        except OAuthQQUser.DoesNotExist:

            openid_token = generic_openid_token(openid)

            return Response({'access_token':openid_token})
        else:
            from rest_framework_jwt.settings import api_settings

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(qquser.user)
            token = jwt_encode_handler(payload)

            return Response({
                "user_id":qquser.user.id,
                "username":qquser.user.username,
                "token":token
            })


    def post(self,request):

        data = request.data
        serializer = OAuthQQUserSerializer(data=data)
        serializer.is_valid(raise_exception=True)

        qquser = serializer.save()

        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(qquser.user)
        token = jwt_encode_handler(payload)

        return Response({
            'user_id': qquser.user.id,
            'username': qquser.user.username,
            'token': token
        })
